import os
import sys
import pandas as pd
from docx import Document

def load_config():
    """读取系统配置

    从当前目录下的config.csv读取系统配置

    Returns:
        1: 替换字典, key为源内容, source为目标内容
        2: 保存路径
    """
    assert os.path.isfile('config.csv'), '错误: 配置文件不存在'
    config = pd.read_csv('config.csv')
    return dict(zip(config['source'], config['target'])), config['result_path'][0]

def get_files():
    """获取全部docx
    
    获取当前目录下所有.docx结尾的文件

    Returns:
        1: 文件数组, 内容为文件名称
    """
    all_files = os.listdir(os.getcwd())
    return [file for file in all_files if os.path.isfile(file) and os.path.splitext(file)[1] == '.docx']

def handle_exception(exc_type, exc_value, exc_traceback):
    print(exc_value)
    os.system('pause')
    sys.exit(1)


def is_all_english(strs: str):
    """判断字符串是否为纯字母

    通过遍历每一个字符是否在英文字母的指定范围内, 判断字符串是否全部为字母

    Returns:
        boolean: 是否为纯字母
    """
    import string
    for i in strs:
        if i not in string.ascii_lowercase + string.ascii_uppercase:
            return False
    return True


def docx_replace(document, replace_dict: dict):
    """替换docx文档中的内容
    
    将docx文档中的指定内容全部替换为目标内容

    Args:
        document: docx文档对象
        replace_dict: 替换字典, key为源内容, source为目标内容
    """
    for para in document.paragraphs:
        for i in range(len(para.runs)):
            for key, value in replace_dict.items():
                if key in para.runs[i].text:
                    para.runs[i].text = para.runs[i].text.replace(key, '' if pd.isnull(value) else value)
                # 如果为纯字母, 则首字母大写的也对应替换掉
                if is_all_english(key) and key.capitalize() in para.runs[i].text:
                    para.runs[i].text = para.runs[i].text.replace(key.capitalize(),
                                                                  '' if pd.isnull(value) else value.capitalize())
    return document


if __name__ == "__main__":
    sys.excepthook = handle_exception
    # 读取相关配置
    replace_dict, result_path = load_config()
    files = get_files()
    # 检测结果文件夹是否存在, 不存在则创建
    if not os.path.exists(result_path):
        os.mkdir(result_path)
    for file in files:
        print('开始转换文件: %s...' % file)
        document = Document(file)
        document = docx_replace(document, replace_dict)
        save_path = result_path + file
        document.save(save_path)
        print('文件转换成功, 保存路径为: %s' % save_path)
    os.system('pause')